import React, { Component } from "react";
import { Menu } from "antd";
import { Link, withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { getTreeData,sortTree } from "@/utils/getTreeData";
import store from "@/store/store"
const { SubMenu } = Menu
const mapStateToProps = (state) => {
  return {
    user: state.user,
    menus: state.menus,
    menuStatus: state.menuStatus,
  };
};

// submenu keys of first level
const rootSubmenuKeys = [];
class CustomMenu extends Component {
  state = {
    openKeys: [],
    selectedKeys: [],
    menusData: [],
    userMenu: sessionStorage.getItem('userMenu'),
    menuName: ''
  };

  // 处理 pathname
  // getOpenKeys = (string) => {
  //   let newStr = "",
  //     newArr = [],
  //     arr = string.split("/").map((i) => "/" + i);
  //   for (let i = 1; i < arr.length - 1; i++) {
  //     newStr += arr[i];
  //     newArr.push(newStr);
  //   }
  //   return newArr;
  // };

  // 页面刷新的时候可以定位到 menu 显示
  componentDidMount() {
    this.setSelect()
    // if (sessionStorage.getItem('userMenu')) {
    //   this.setState({
    //     menu: JSON.parse(sessionStorage.getItem('userMenu'))
    //   })
    // }
    // if (window.performance) {
    //   //表示页面刷新了
    //   store.dispatch({
    //     type: 'ClearSearchValues',
    //   })
    // }
  }

  setSelect = () => {
    const { userMenu } = this.state
    let { pathname } = this.props.location;
    let openKeys = []
    let menu = userMenu ? JSON.parse(userMenu) : []
    let filterMenu = menu.filter(v => pathname === v.menuUrl)
    let menuName = filterMenu[0] ? filterMenu[0].menuName : ''
    if (filterMenu.length) {
      openKeys.push(filterMenu[0].menuParentId)
      if (filterMenu[0].oneLevelId) openKeys.push(filterMenu[0].oneLevelId)
    }
    sessionStorage.setItem('menuName', menuName)
    this.setState({
      selectedKeys: [pathname],
      openKeys,
      menuName
    });
  }

  //递归处理数据  使用menuUrl生成动态key
  recurrenceData = (arr) => {
    for (let i = 0; i < arr.length; i++) {
      arr[i].key = arr[i].menuUrl;
      if (arr[i].children && arr[i].children.length > 0) {
        this.recurrenceData(arr[i].children);
      }
    }
    return arr;
  };

  // // 点击面包屑导航时 侧边栏同步响应
  componentDidUpdate(prevProps, prevState) {
    let { pathname } = this.props.location;
    if (prevProps.location.pathname !== pathname) {
      this.setSelect()
    }
  }
  onOpenChange = (keys) => {
    const { openKeys } = this.state
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({
        openKeys: keys,
      });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  };
  // 只展开一个 SubMenu
  // onOpenChange = (openKeys, a, b) => {
  //   if (openKeys.length < 4) {
  //     this.setState({
  //       openKeys,
  //     });
  //     return;
  //   }

  //   // 最新展开的 SubMenu
  //   const latestOpenKey = openKeys[openKeys.length - 1];
  //   // 这里与定义的路由规则有关
  //   if (latestOpenKey.includes(openKeys[0])) {
  //     this.setState({
  //       openKeys,
  //     });
  //   } else {
  //     this.setState({
  //       openKeys: [latestOpenKey],
  //     });
  //   }
  // };

  renderMenuItem = ({ key, menuIcon, menuName }) => {
    return (
      <Menu.Item key={key}>
        <Link to={key}>
          <span className={"menuIcon"}>
            &nbsp;
            <span style={{ marginRight: 10 }} className={[`iconfont ${menuIcon}`]} />
          </span>
          <span>{menuName}</span>
        </Link>
      </Menu.Item>
    );
  };

  // 循环遍历数组中的子项 subs ，生成子级 menu
  renderSubMenu = ({ menuName, menuIcon, children, menuId }) => {
    return (
      <Menu.SubMenu
        key={menuId}
        title={
          <span className={"menuIcon"}>
            &nbsp;
            {menuIcon && <span style={{ marginRight: 10 }} className={[`iconfont ${menuIcon}`]} />}
            <span>{menuName}</span>
          </span>
        }
      >
        {children &&
          children.map((item) => {
            return item.children && item.children.length > 0
              ? this.renderSubMenu(item)
              : this.renderMenuItem(item);
          })}
      </Menu.SubMenu>
    );
  };

  render() {
    let { openKeys, selectedKeys } = this.state;
    const menus = sessionStorage.getItem("userMenu");
    let menusData = [];
    if (menus && menus.length > 0) {
      if (Object.prototype.toString.call(menus) === "[object Array]") {
        menusData = this.recurrenceData(sortTree(getTreeData(menus)) );
      } else {
        try {
          menusData = this.recurrenceData(sortTree(getTreeData(JSON.parse(menus))));
        } catch (e) {
          console.log(e);
        }
      }
    }
    let menusResult = menusData;
    return (
      <Menu
        className={this.props.collapsed ? "menuLeft" : ""}
        mode="inline"
        theme="dark"
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        onClick={({ key }) => {
          localStorage.removeItem('searchValue')
          localStorage.removeItem('pageNo')
          store.dispatch({
            type: 'ClearSearchValues',
          })
          store.dispatch({
            type: 'ClearPageTabValue',
          })
          store.dispatch({
            type: 'ClearDataSource',
          })
          sessionStorage.removeItem('searchValue')
          this.props.history.push(key);
          this.setState({ selectedKeys: [key] });
        }}
        onOpenChange={this.onOpenChange}
      >
        {menusResult &&
          menusResult.map((item) => {
            rootSubmenuKeys.push(item.menuId)
            return item && item.children && item.children.length > 0
              ? this.renderSubMenu(item)
              : this.renderMenuItem(item);
          })}
      </Menu>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    uploadMenuStatus: (data) => dispatch({ type: "setMenuStatus", data }),
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(CustomMenu));
